package com.boarsoft.flow.store;

import java.io.File;

import org.codehaus.plexus.util.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.boarsoft.common.Util;
import com.boarsoft.flow.core.FlowConfig;

/**
 * 基于文件实现的简单流程文件存储器
 * 
 * @author Mac_J
 *
 */
public class SimpleFlowStoreImpl implements SimpleFlowStore {
	private static final Logger log = LoggerFactory.getLogger(SimpleFlowStoreImpl.class);

	@Override
	public boolean delete(String id) {
		String from = this.getDiagramPath(id);
		log.info("Delete flow diagram from {}", from);
		try {
			File d = new File(from);
			if (d.exists()) {
				File p = null;
				do {
					p = d.getParentFile();
					FileUtils.deleteDirectory(d);
				} while (p != null && p.exists() && p.list().length == 0);
			}
		} catch (Exception e) {
			log.info("Error on delete flow diagram from {}", from, e);
			return false;
		}
		return true;
	}

	public boolean copy(String oid, String nid) {
		String from = this.getDiagramPath(oid);
		String to = this.getDiagramPath(nid);
		log.info("Copy flow diagram from {} to {}", from, to);
		try {
			FileUtils.copyDirectory(new File(from), new File(to));
		} catch (Exception e) {
			log.info("Error on copy flow diagram from {} to {}", from, to, e);
			return false;
		}
		return true;
	}

	@Override
	public boolean move(String oid, String nid) {
		String from = this.getDiagramPath(oid);
		String to = this.getDiagramPath(nid);
		log.info("Copy flow diagram from {} to {}", from, to);
		try {
			FileUtils.copyDirectory(new File(from), new File(to));
		} catch (Exception e) {
			log.info("Error on move flow diagram from {} to {}", from, to, e);
			return false;
		}
		return true;
	}

	@Override
	public String getDiagramPath(String id) {
		return new StringBuilder(FlowConfig.DIAGRAMS_DIR)//
				.append(this.getRelativePath(id)).toString();
	}

	@Override
	public String getRelativePath(String id) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < id.length(); i += 8) {
			sb.append("/").append(id.substring(i, Math.min(i + 8, id.length())));
		}
		return sb.toString();
	}

	@Override
	public String getXmlFilePath(String path, String code) {
		if (Util.strIsEmpty(path)) {
			path = FlowConfig.APP_ROOT;
		}
		return new StringBuilder(path).append(FlowConfig.FLOWS_DIR)//
				.append("/").append(code).append(".xml").toString();
	}
}